<?php

namespace HPay;


use think\Log;

class HPayApi
{
    private $merchant = "hpay033";

    private $secretKey = "7a8a574b99dd5063dde441e7be0cecbf";

    private $callbackKey = "7a8a574b99dd5063dde441e7be0cecbf";

    /**
     * constructor.
     */
    function __construct()
    {
    }

    /**
     * 获取API接口URL根地址
     * @return string
     */
    public static function getApiUrl()
    {
        return "https://hpay.la2568.site/";
    }

    /**
     * 发送请求
     * @param $apiPath
     * @param array $params
     * @param string $requestType
     * @param string $headers
     * @return mixed
     */
    public function request($apiPath, $params = [], $requestType = 'POST', $headers = '')
    {
        $url = self::getApiUrl();

        $timeout = 30;
        $params['merchant'] = $this->merchant;
        $params['sign'] = $this->sign($params);
        $params_encode = json_encode($params);
        Log::info('request params:' . $params_encode);

        //根据请求类型设置特定参数
        $opts = array(
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url . $apiPath,
            CURLOPT_SSL_VERIFYPEER => FALSE,//不验证证书
        );
        if ($headers != "") {
            $opts[CURLOPT_HTTPHEADER] = $headers;
        } else {
            $opts[CURLOPT_HTTPHEADER] = array('Content-type: application/x-www-form-urlencoded; charset=utf-8');
        }
        switch (strtoupper($requestType)) {
            case "GET" :
                $opts[CURLOPT_HTTPGET] = true;
                $opts[CURLOPT_URL] = $url . $apiPath . '?' . http_build_query($params);
                $opts[CURLOPT_ENCODING] = '';
                $opts[CURLOPT_CUSTOMREQUEST] = 'GET';
                break;
            case "POST":
                $opts[CURLOPT_POST] = true;
                $opts[CURLOPT_CUSTOMREQUEST] = "POST";
                $opts[CURLOPT_POSTFIELDS] = http_build_query($params);
                break;
            case "PUT" :
                $opts[CURLOPT_CUSTOMREQUEST] = "PUT";
                $opts[CURLOPT_POSTFIELDS] = $params_encode;
                break;
            case "DELETE":
                $opts[CURLOPT_CUSTOMREQUEST] = "DELETE";
                $opts[CURLOPT_POSTFIELDS] = $params_encode;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);

        $result = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        if (!empty($err)) {
            Log::error('hpay api request:' . json_encode($result) . ',error:' . json_encode($err));
        }
        return json_decode($result, true);
    }

    /**
     * post请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function post($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'POST', $headers);
    }

    /**
     * get请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function get($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'GET', $headers);
    }

    /**
     * 参数ascii排序,生成参数字符串
     * @param array $params
     * @return false|string
     */
    public function asc_sort($params = array())
    {
        if (!empty($params)) {
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    if (!empty($val) && $k != 'sign') {
                        $str .= $k . '=' . $val . '&';
                    }
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return false;
    }

    /**
     * 签名
     * @param $params
     * @return string
     */
    protected function sign($params)
    {
        $tempStr = $this->asc_sort($params);
        $signStr = $tempStr . "&key=" . $this->secretKey;
        return md5($signStr);
    }

    /**
     * 回调签名
     * @param $params
     * @return string
     */
    public function callbackSign($params)
    {
        $tempStr = $this->asc_sort($params);
        $signStr = $tempStr . "&key=" . $this->callbackKey;
        return md5($signStr);
    }
}
